package com.tomato.study.jvm.juc;

/**
 *  VolatileTest
 *
 * @author lizhifu
 * @date 2022/3/20
 */
public class VolatileTest {
    public static volatile int race = 0;
    private static final int THREADS_COUNT = 20;

    /**
     * race 自增
     */
    public static void increase() {
        race++;
    }

    public static void main(String[] args) {
        // 线程数组
        Thread[] threads = new Thread[THREADS_COUNT];
        // 创建线程
        for (int i = 0; i < THREADS_COUNT; i++) {
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j < 10000; j++) {
                        race++;
                    }
                }
            });
            // 执行
            threads[i].start();
        }
        //  等待所有累加线程都结束
        while (Thread.activeCount() > 1){
            Thread.yield();
        }
        System.out.println(race);
    }
}
